package com.example.asus.keshe;

import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

/**
 * Created by k42 on 2018-05-05.
 */

public class LoginActivity extends Activity implements View.OnClickListener{

    private MySqliteHelper mySqliteHelper;

    private EditText editText,editText1;

    private Button button;
    private Button button1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.login);

        editText = (EditText)findViewById(R.id.editText13);
        editText1 = (EditText)findViewById(R.id.editText14);

        mySqliteHelper = new MySqliteHelper(this);

        button = (Button)findViewById(R.id.button_login);
        button1 = (Button)findViewById(R.id.button_r);

        button.setOnClickListener(this);
        button1.setOnClickListener(this);

    }

    /**
     * 判断登录是否成功
     * @param username
     * @param password
     * @return true:成功  false:失败
     */
    public boolean isLogin(String username,String password){
        boolean flag = false;
        String sql = "select count(*) num from person where name=? and password=?";
        String[] args = {username,password};

        SQLiteDatabase db = mySqliteHelper.getWritableDatabase();
        Cursor cursor = db.rawQuery(sql,args);
        if(cursor != null){
            if(cursor.moveToNext()){
                int num = cursor.getInt(cursor.getColumnIndex("num"));
                if(num > 0) flag = true; //有此记录
            }
            cursor.close();
        }

        return flag;
    }

    @Override
    public void onClick(View v) {
        String username = editText.getText().toString();
        String password = editText1.getText().toString();


        switch (v.getId()){ //判断点击的按钮的id
            case R.id.button_login:
                if(isLogin(username,password)){ //成功
                Intent intent = new Intent();
                intent.setClass(this,GridViewActivity.class);
                startActivity(intent);
            }else { //失败
                Toast.makeText(this,"用户名或密码错误!",Toast.LENGTH_SHORT).show();
            }
            break;

            case R.id.button_r:
                Intent intent3 = new Intent();
                intent3.setClass(this,RegisterActivity.class);
                startActivity(intent3);
                break;
        }

    }
}
